<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区 -->
    <el-card>
      <!-- 警告区域 -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        show-icon
        :closable="false"
      >
      </el-alert>
      <!-- 选择商品分类区域 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类: </span>
          <!-- 级联选择框 -->
          <el-cascader
            v-model="selectedCateKeys"
            :options="goodsCategoryList"
            :props="cateProps"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tabs标签页 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <!-- 法一 -->
          <!-- 添加参数按钮，判断其是否禁用
          <el-row>
            <el-col>
              <el-button
                type="primary"
                :disabled="false"
                size="mini"
                v-if="this.selectedCateKeys.length"
                >添加参数</el-button
              >
              <el-button type="primary" :disabled="true"  size="mini" v-else
                >添加参数</el-button
              >
            </el-col>
          </el-row> -->
          <el-button
            type="primary"
            :disabled="isBtnDisabled"
            size="mini"
            @click="addDialogVisible = true"
            >添加参数</el-button
          >

          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(items, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  :disable-transitions="true"
                  @close="handleClose(i, scope.row)"
                >
                  {{ items }}
                </el-tag>
                <!-- 输入的文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 输入的按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ 添加属性</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="showEidtDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="DeleteDateStyle(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <!-- 法一 -->
          <!-- 添加参数按钮，判断其是否禁用
          <el-row>
            <el-col>
              <el-button
                type="primary"
                :disabled="false"
                v-if="this.selectedCateKeys.length"
                >添加参数</el-button
              >
              <el-button type="primary" :disabled="true" v-else
                >添加参数</el-button
              >
            </el-col>
          </el-row> -->
          <!-- 法二 -->
          <el-button
            type="primary"
            :disabled="isBtnDisabled"
            size="mini"
            @click="addDialogVisible = true"
            >添加属性</el-button
          >

          <!-- 动态参数表格 -->
          <el-table :data="onlyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(items, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  :disable-transitions="true"
                  @close="handleClose(i, scope.row)"
                >
                  {{ items }}
                </el-tag>
                <!-- 输入的文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 输入的按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ 添加属性</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column
              label="属性名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="showEidtDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="DeleteDateStyle(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addDialogVisible"
      width="40%"
      @close="addDialogClosed"
    >
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateDataList">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 点击编辑显示的对话框 -->
    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="editDialogVisible"
      width="40%"
      @close="editDialogClosed"
    >
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateEidtList">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 商品分类列表
      goodsCategoryList: [],
      // 级联选择框的配置对象
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      //   级联选择框双向绑定的数组
      selectedCateKeys: [],
      //   初始选择的数据
      activeName: 'many',
      //   获取动态属性的参数
      manyTableData: [],
      //   获取静态属性的参数
      onlyTableData: [],
      // 控制添加对话框的显示与隐藏
      addDialogVisible: false,
      // 添加参数的表单数据对象
      addForm: {},
      // 添加表单的验证规则对象
      addFormRules: {
        attr_name: [
          {
            required: true,
            // TODO：在点击添加参数或者添加属性时出现不同的提示
            message: '请输入参数或者属性名称',
            trigger: 'blur'
          }
        ]
      },
      // 控制修改对话框的展示与隐藏
      editDialogVisible: false,
      // 修改的表单数据对象
      editForm: {
        attr_name: ''
      },
      // 修改表单的验证规则对象
      editFormRules: {
        attr_name: [
          {
            required: true,
            // TODO：在点击添加参数或者添加属性时出现不同的提示
            message: '请输入修改的名称',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.getGoodsCategory()
  },
  methods: {
    // 获取所有商品分类的列表
    async getGoodsCategory() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        this.$message.error('获取数据失败!')
      }
      this.goodsCategoryList = res.data
    },
    // 根据所选分类的id，和当前所处的面板，获取对应的属性
    async getArgumentList() {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName }
        }
      )
      if (res.meta.status !== 200) {
        this.$message.error('获取参数列表数据失败，请稍后再试！')
      }

      res.data.forEach((items) => {
        items.attr_vals = items.attr_vals ? items.attr_vals.split(',') : []
        // 控制文本框的显示与隐藏
        items.inputVisible = false
        // 文本框中输入的值
        items.inputValue = ''
      })
      //   判断数据属于哪一个
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    // 级联选择框选项发生变化,触发这个函数
    handleChange() {
      // 控制级联选择器选择三级列表
      if (this.selectedCateKeys.length !== 3) {
        this.selectedCateKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return this.$message.error('请选择三级分类设置!')
      }
      // 获取参数列表
      this.getArgumentList()
    },

    // tab页签点击事件的处理函数
    handleTabClick() {
      if (!this.selectedCateKeys.length) {
        return this.$message.error('请选择需要获取数据的商品！')
      }
      this.getArgumentList()
    },
    // 关闭对话框清空数据
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 点击按钮添加参数
    updateDataList() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return

        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 201) {
          return this.$message.error('添加数据失败！')
        }
        this.getArgumentList()
        this.$message.success('添加数据成功！')
        // 关闭对话框
        this.addDialogVisible = false
      })
    },
    // 点击编辑按钮，展示修改的对话框
    async showEidtDialog(id) {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${id}`,
        {
          params: { attr_sel: this.activeName }
        }
      )
      if (res.meta.status !== 200) {
        return this.$error.message('查询信息失败！')
      }
      console.log(res.data)
      this.editForm = res.data
      // 点击按钮显示对话框
      this.editDialogVisible = true
    },
    // 关闭编辑对话框时重置表单
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 点击确定发起请求修改数据
    updateEidtList() {
      // 对表单数据进行验证
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('修改数据失败，请稍后再试！')
        }
        this.$message.success('修改成功！')
        this.getArgumentList()
        // 关闭对话框
        this.editDialogVisible = false
      })
    },
    // 点击删除删除当前行数据
    async DeleteDateStyle(id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该参数, 是否删除?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)

      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除！')
      }

      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${id}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败，请稍后再试!')
      }
      this.getArgumentList()
      this.$message.success('删除成功！')
    },
    handleClose(i, row) {
      // 点击删除当前项
      row.attr_vals.splice(i, 1)
      // 发起请求修改参数
      this.updateParams(row)
    },
    // 点击按钮显示input输入框
    showInput(row) {
      row.inputVisible = true
      // 自动获取焦点
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 按下enter键添加标签  // 失去焦点触发添加数据
    async handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      // 发起请求保存本次结构
      this.updateParams(row)
    },
    async updateParams(row) {
      //  发起请求
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.cat_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(',')
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error(`修改${row.attr_name}参数失败!`)
      }
      this.$message.success(`修改${row.attr_name}参数成功！`)
    }
  },

  // 计算属性
  computed: {
    // 计算出属性的布尔值
    isBtnDisabled() {
      if (this.selectedCateKeys.length !== 3) {
        return true
      }
      return false
    },
    // 当前选中的三级分类的id
    cateId() {
      if (this.selectedCateKeys.length) {
        return this.selectedCateKeys[2]
      }
      return null
    },
    // 动态计算标题的文本
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  }
}
</script>

<style lang="less" scoped>
.cat_opt {
  margin: 20px 0;
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
}
</style>
